﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EraNet.Core;
using EraNet.Core.Caching;
using EraNet.Core.Data;
using EraNet.Core.Events;
using EraNet.Core.Model.SysManage;
using EraNet.Common;

namespace EraNet.Services.SysManage
{
    public class AreaInfoService : IAreaInfoService
    {
        #region Constants
        private const string AREAINFO_ALL_KEY = "Era.AreaInfo.Mark8276n36";
        private const string AREACONFIG_ALL_KEY = "Era.AreaConfig.Mark0jslwr5";
        #endregion

        #region Fields
        /// <summary>
        /// 地市信息
        /// </summary>
        private readonly IRepository<AreaInfo> _areainfoRepository;
        /// <summary>
        /// 地市配置信息
        /// </summary>
        private readonly IRepository<AreaInfoConfig> _areainfoconfigRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        #endregion

        #region Ctor
        public AreaInfoService(IRepository<AreaInfo> areainfoRepository,IRepository<AreaInfoConfig> areainfoconfigRepository, ICacheManager cacheManager, IEventPublisher eventPublisher)
        {
            this._areainfoRepository = areainfoRepository;
            this._areainfoconfigRepository = areainfoconfigRepository;
            this._cacheManager = cacheManager;
            this._eventPublisher = eventPublisher;
        }
        #endregion

        #region
        #region 地市信息
        public int InsertAreaInfo(AreaInfo model)
        {
            if (model == null)
                throw new ExtException("Null AraaInfo Model");
            //验证是否已经存在
            if (GetAllAreaInfo().Where(c => c.AreaCode == model.AreaCode).Count() > 0) return 2;
            int rs = _areainfoRepository.Insert(model) > 0 ? 1 : 0;
            //数据处理成功，更新缓存
            if (rs > 0)
            {
                _cacheManager.Remove(AREAINFO_ALL_KEY);

                //event notification
                _eventPublisher.EntityInserted(model);
            }
                return rs;
        }

        public int UpdateAreaInfo(AreaInfo model)
        {
            if (model == null)
                throw new ExtException("Null AraaInfo Model");
            //验证是否已经存在
            if (GetAllAreaInfo().Where(c => c.Id!=model.Id &&c.AreaCode == model.AreaCode).Count() > 0) return 2;
            int rs = _areainfoRepository.Update(model) > 0 ? 1 : 0;
            //数据处理成功，更新缓存
            if (rs > 0)
            {
                _cacheManager.Remove(AREAINFO_ALL_KEY);

                //event notification
                _eventPublisher.EntityUpdated(model);
            }
            return rs;
        }

        public AreaInfo GetAreaInfoByCode(string areacode)
        {
            if (string.IsNullOrEmpty(areacode)) return null;

            return  GetAllAreaInfo().Where(c => c.AreaCode == areacode).FirstOrDefault() ;
        }

        /// <summary>
        /// 取全部信息，并缓存
        /// </summary>
        /// <returns></returns>
        public IList<AreaInfo> GetAllAreaInfo()
        {
            return _cacheManager.Get(AREAINFO_ALL_KEY, () =>
            {
                var p = _areainfoRepository.Table.ToList();
                return p;
            });
        }
        #endregion

        #region
        public int InsertAreaConfig(AreaInfoConfig model)
        {
            if (model == null)
                throw new ExtException("Null AraaInfo Model");
            //验证是否已经存在
            if (GetAllAreaConfig().Where(c => c.AreaCode == model.AreaCode).Count() > 0) return 2;
            int rs = _areainfoconfigRepository.Insert(model) > 0 ? 1 : 0;
            //数据处理成功，更新缓存
            if (rs > 0)
            {
                _cacheManager.Remove(AREACONFIG_ALL_KEY);

                //event notification
                _eventPublisher.EntityInserted(model);
            }
            return rs;
        }

        public int UpdateAreaConfig(AreaInfoConfig model)
        {
            if (model == null)
                throw new ExtException("Null AraaInfo Model");
            //验证是否已经存在
            if (GetAllAreaConfig().Where( c =>c.Id!=model.Id&&c.AreaCode == model.AreaCode).Count() > 0) return 2;
            int rs = _areainfoconfigRepository.Insert(model) > 0 ? 1 : 0;
            //数据处理成功，更新缓存
            if (rs > 0)
            {
                _cacheManager.Remove(AREACONFIG_ALL_KEY);

                //event notification
                _eventPublisher.EntityUpdated(model);
            }
            return rs;
        }

        public int DeleteAreaConfig(int configid)
        {
            var m = _areainfoconfigRepository.GetById(configid);

            int rs = _areainfoconfigRepository.Delete(m) > 0 ? 1 : 0;
            //数据处理成功，更新缓存
            if (rs > 0)
            {
                _cacheManager.Remove(AREACONFIG_ALL_KEY);

                //event notification
                _eventPublisher.EntityDeleted(m);
            }
            return rs;
        }

        public AreaInfoConfig GetAreaConfigByCode(string areacode)
        {
            if (string.IsNullOrEmpty(areacode)) return null;

            return GetAllAreaConfig().Where(c => c.AreaCode == areacode).FirstOrDefault();
        }

        public AreaInfoConfig GetAreaConfigByArea(string province, string city)
        {
            AreaInfoConfig cfg = null;
            if (string.IsNullOrEmpty(province)) return null;
            if (!string.IsNullOrEmpty(city))
            {
                AreaInfo m = _areainfoRepository.Table.Where(c => c.ShortName == city).FirstOrDefault();
                if (m != null && !string.IsNullOrEmpty(m.AreaNames))
                {
                    cfg = GetAllAreaConfig().Where(c => c.AreaCode == m.AreaCode).FirstOrDefault();
                }
                if (cfg != null) return cfg;
            }
            AreaInfo p = _areainfoRepository.Table.Where(c => c.ShortName == province).FirstOrDefault();
            if (p != null && !string.IsNullOrEmpty(p.AreaNames))
            {
                cfg = GetAllAreaConfig().Where(c => c.AreaCode == p.AreaCode).FirstOrDefault();
            }
            return cfg;
        }

        public bool VerifyArea()
        {
            //身份证登录 获取其IP
            string Ipstr = Common.Request.GetIpDetails();
            //获取IP地址信息
            Core.Model.Common.AreaIp areaip = Common.JSONHelper.ParseJSON<Core.Model.Common.AreaIp>(Ipstr);
            //如果没有有成功获取Ip 
            if (areaip.ret != 1)
                return false;

            #region 获取配置，判断

            ////省
            //AreaInfoConfig sconf = GetAreaConfigByCode(areaip.data.region_id);
            //if (sconf != null && sconf.IsOpen == true) return true;
            ////市
            //AreaInfoConfig conf = GetAreaConfigByCode(areaip.data.city_id);
            AreaInfoConfig conf = GetAreaConfigByArea(areaip.province, areaip.city);
            //如果配置了需要验证是否开放地市，
            if (conf == null || conf.IsOpen == false)
                return false;
            #endregion
            return true;
        }

        private IList<AreaInfoConfig> GetAllAreaConfig()
        {
            return _cacheManager.Get(AREACONFIG_ALL_KEY, () =>
            {
                var p = _areainfoconfigRepository.Table.ToList();
                return p;
            });
        }

        #endregion
        #endregion
    }
}
